package com.wn55.hrms.interceptors;

import com.wn55.hrms.util.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.SignatureException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.logging.Logger;

@Slf4j
public class PermissionInterceptor implements HandlerInterceptor {

    JwtUtil jwtUtil = JwtUtil.getInstance();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        response.setHeader("Access-control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        response.setHeader("Access-Control-Allow-Headers", request.getHeader("Access-Control-Request-Headers"));

        //查看以下  客户请求的资源
        String path = request.getServletPath();
        System.out.println("=========" + path + "=========");

        //跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if ("OPTIONS".equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }
        return true;
        //请求头信息  token
       /* String token = request.getHeader("token");
        log.info(token);
        if (token == null){
            //没有登录
            String json = "{\"code\":201,\"msg\":\"请先登录！\"}";
            response.getOutputStream().write(json.getBytes());
            return false ;
        }else {
            try {
                Claims claims = jwtUtil.parseToken(token);
                //成功登录过
                return true ;
            }catch (ExpiredJwtException e1){
                e1.printStackTrace();
                String json = "{\"code\":201,\"msg\":\""+e1.getMessage()+"\"}";
                //token 过期
                response.getOutputStream().write(json.getBytes());
                return false ;
            }catch (SignatureException e2){
                e2.printStackTrace();
                //密钥 错误
                String json = "{\"code\":201,\"msg\":\""+e2.getMessage()+"\"}";
                response.getOutputStream().write(json.getBytes());
                return  false ;
            }catch (RuntimeException e3){
                e3.printStackTrace();
                //解析token 出错
                String json = "{\"code\":201,\"msg\":\""+e3.getMessage()+"\"}";
                return false ;
            }
    }*/
}
}
